package com.sunbim.rsrv.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunbim.rsrv.common.exception.RequestException;
import com.sunbim.rsrv.mapper.RelicsMapper;
import com.sunbim.rsrv.mapper.RiskManageMapper;
import com.sunbim.rsrv.pojo.RiskManage;
import com.sunbim.rsrv.service.RiskManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 管理风险 服务实现类
 * </p>
 *
 * @author yuhui
 * @since 2021-12-30
 */
@Service
public class RiskManageServiceImpl extends ServiceImpl<RiskManageMapper, RiskManage> implements RiskManageService {

    @Autowired
    RiskManageMapper riskManageMapper;
    @Autowired
    RelicsMapper relicsMapper;

    @Override
    public RiskManage selectByRelicsId(Integer userId, Integer relicsId) {
        // 查询风险
        QueryWrapper<RiskManage> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("relics_id", relicsId);
        RiskManage riskManage = riskManageMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(riskManage)) throw new RequestException("文物id: " + relicsId + " 的风险数据不存在");

        int level = getLevel(riskManage.getScore());
        riskManage.setLevel(level);
        return riskManage;
    }

    /**
     * 计算管理风险等级
     * 一级：得分0-5分
     * 二级：得分6-20分
     * 三级：得分21-45分
     * 四级：得分46-73分
     */
    public static int getLevel(Integer score) {
        int level;
        if (score == null || score <= 5) level = 1;
        else if (score <= 20) level = 2;
        else if (score <= 45) level = 3;
        else level = 4;
        return level;
    }

    @Override
    public void updateByRiskId(RiskManage params) {
        boolean isIdExist = riskManageMapper.idExist(params.getId());
        if (!isIdExist) throw new RequestException("风险id: " + params.getId() + " 不存在");

        int score = params.getDefense() + params.getFire() + params.getFirefighting() + params.getThunder() + params.getVisitor();
        params.setScore(score);
        riskManageMapper.updateById(params);
    }

    public List<RiskManage> getAllByUserId(Integer userId) {
        QueryWrapper<RiskManage> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return riskManageMapper.selectList(wrapper);
    }
}
